package com.parking.renters.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.parking.common.core.model.PageInfo;
import com.parking.common.core.model.RedisKey;
import com.parking.common.core.model.Result;
import com.parking.common.core.model.StateData;
import com.parking.common.web.util.RedisUtil;
import com.parking.common.web.util.SmsUtil;
import com.parking.renters.dao.RentersAccountLogsMapper;
import com.parking.renters.dao.RentersInfoMapper;
import com.parking.renters.entity.Renters;
import com.parking.renters.dao.RentersMapper;
import com.parking.renters.entity.RentersAccountLogs;
import com.parking.renters.entity.RentersInfo;
import com.parking.renters.exception.RentersException;
import com.parking.renters.exceptionCode.RentersExceptionCode;
import com.parking.renters.inter.CertifiedClient;
import com.parking.renters.model.stallCall.dto.RentersDto;
import com.parking.renters.model.stallCall.dto.RentersLoginDTO;
import com.parking.renters.model.stallCall.form.RegisterForm;
import com.parking.renters.model.stallCall.form.RentersLoginForm;
import com.parking.renters.model.stallCall.form.RentersPhoneForm;
import com.parking.renters.model.stallCall.form.SelectRenterForm;
import com.parking.renters.service.RentersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.security.cert.CertificateEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 彭于晏
 * @since 2023年11月29日
 */
@Service
public class RentersServiceImpl extends ServiceImpl<RentersMapper, Renters> implements RentersService {
    @Resource
    private RentersAccountLogsMapper rentersAccountLogsMapper;
    @Resource
    private RentersInfoMapper rentersInfoMapper;
    @Resource
    private RentersMapper rentersMapper;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private SmsUtil smsUtil;
    @Resource
    private CertifiedClient  certifiedClient;

    /***
     * 出租客注册
     * @param form
     */
    @Override
    @Transactional
    public void register(RegisterForm form) throws Exception {
        String code = redisUtil.get(RedisKey.rentersRegisterCode(form.getRentersInfoTel()));
        System.out.println("验证码"+code);
        if (code==null||!form.getCode().equals(code)) {
            throw new RentersException(RentersExceptionCode.RENTERS_PHONE_CODE_ISNO);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_tel",form.getRentersInfoTel());
        RentersInfo info = rentersInfoMapper.selectOne(wrapper);
        if (info!=null){
            throw new RentersException(RentersExceptionCode.RENTERS_IS_NOT_NULL_TEL);
        }
        QueryWrapper<Renters> wrapper1 = new QueryWrapper<>();
        wrapper1.like("renters_account",form.getRentersAccount());
        Renters renters = rentersMapper.selectOne(wrapper1);
        if (renters!=null){
            throw new RentersException(RentersExceptionCode.RENTERS_IS_NOT_NULL_ACCOUNT);
        }
        Renters renters1 = BeanUtil.toBean(form, Renters.class);
        renters1.setRentersState(StateData.RENDERS_STATE_ENABLE);
        renters1.setAccountRole(StateData.ROLE_STATE_RENTERS);
        renters1.setRentersAddPerson(form.getRentersAccount());
        renters1.setRentersAddTime(LocalDateTime.now());
        renters1.setRentersUpdatePerson(form.getRentersAccount());
        renters1.setRentersUpdateTime(LocalDateTime.now());
        rentersMapper.insert(renters1);
        RentersInfo rentersInfo = BeanUtil.toBean(form, RentersInfo.class);
        rentersInfo.setRentersInfoTel(form.getRentersInfoTel());
        rentersInfo.setRentersId(renters1.getRentersId());
        rentersInfo.setRentersInfoName(renters1.getRentersAccount());
        rentersInfo.setRentersRealNameState(StateData.RENTERS_REAL_NAME_STATE_NO);
        rentersInfoMapper.insert(rentersInfo);
    }

    /***
     * 发送出租客注册验证码
     * @param phone
     * @throws Exception
     */
    @Override
    public void sendRegisterCode(String phone) throws Exception{
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_tel",phone);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        if (rentersInfo!=null) {
            throw new RentersException(RentersExceptionCode.RENTERS_IS_NOT_NULL_TEL);
        }
        //一分钟内不能再次发送手机验证码
        if (redisUtil.exist((RedisKey.rentersRegisterCodeOnMinute(phone)))) {
            throw new RentersException(RentersExceptionCode.RENTERS_PHONE_ONE_MINUTER);
        }
        //消息队列修改日志信息
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        rabbitTemplate.convertAndSend("sendRegisterCode",map);
    }

    /***
     * 出租客账号登录
     * @param form
     * @param response
     * @return
     */
    @Override
    public RentersLoginDTO login(RentersLoginForm form, HttpServletResponse response) {
        //登录判断
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_account",form.getRentersAccount());
        wrapper.eq("renters_pass",form.getRentersPass());
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if(renters.getRentersState()!=StateData.RENDERS_STATE_ENABLE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        if (renters.getAccountRole()!=StateData.ROLE_STATE_RENTERS){
            throw new RentersException(RentersExceptionCode.RENTERS_ROLE_IS_NOT_RENTERS);
        }
        QueryWrapper<RentersInfo> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("renters_id",renters.getRentersId());
        RentersInfo info = rentersInfoMapper.selectOne(wrapper2);
        RentersLoginDTO dto = BeanUtil.toBean(info, RentersLoginDTO.class);
        dto.setRentersAccount(renters.getRentersAccount());
        //用户登录日志储存在消息队列
        RentersAccountLogs rentersAccountLogs = new RentersAccountLogs();
        rentersAccountLogs.setRentersLoginName(renters.getRentersAccount());
        rentersAccountLogs.setRentersAccountId(renters.getRentersId());
        rentersAccountLogs.setRentersLoginTime(LocalDateTime.now());
        rentersAccountLogs.setRentersLoginState(StateData.RENTERS_LOGS_ISNOT_LOGIN);
        HashMap<String, Object> map = new HashMap<>();
        map.put("rentersAccountLogs",rentersAccountLogs);
        rabbitTemplate.convertAndSend("rentersAccountLogs",map);
        return dto;
    }

    /***
     * 出租客验证码登录
     * @param form
     * @param response
     * @return
     */
    @Override
    public RentersLoginDTO codeLogin(RentersPhoneForm form,HttpServletResponse response) {
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_tel",form.getPhone());
        RentersInfo info = rentersInfoMapper.selectOne(wrapper);
        if (info==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        System.out.println(form.getPhone());
        System.out.println();
        String code =redisUtil.get(RedisKey.rentersLoginCode(form.getPhone()));
        //判断验证
        if (!code.equals(form.getCode())) {
            throw new RentersException(RentersExceptionCode.RENTERS_PHONE_CODE_ISNO);
        }
        Renters renters = rentersMapper.selectById(info.getRentersId());
        RentersLoginDTO dto = BeanUtil.toBean(info, RentersLoginDTO.class);
        dto.setRentersAccount(renters.getRentersAccount());
        return dto;
    }

    /***
     * 发送出租客登录验证码
     * @param phone
     */
    @Override
    public void sendLoginCode(String phone) {
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_tel",phone);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        if (rentersInfo==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
//        Renters renters = rentersMapper.selectById(rentersInfo.getRentersId());
//        if (renters.getRentersState()!= StateData.RENDERS_STATE_ENABLE) {
//            throw new RentersException(RentersExceptionCode.RENTERS_PHONE_CODE_ISNO);
//        }
        if (redisUtil.exist(RedisKey.rentersLoginCodeOnMinute(phone))) {
            throw new RentersException(RentersExceptionCode.RENTERS_PHONE_ONE_MINUTER);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        rabbitTemplate.convertAndSend("sendLoginCode",map);
    }

    /***
     * 退出登录
     * @param rentersId
     */
    @Override
    public void loginOff(Integer rentersId) {
        RentersAccountLogs logs = rentersAccountLogsMapper.selectById(rentersId);
        logs.setRentersLoginState(StateData.RENTERS_LOGS_LOGIN);
    }

    /***
     * 根据id查询出租客账号
     * @param rentersId
     * @return
     */
    @Override
    public RentersDto selectRentersById(Integer rentersId) {
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()!=StateData.RENDERS_STATE_ENABLE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        RentersDto dto = BeanUtil.toBean(renters, RentersDto.class);
        return dto;
    }

    /***
     * 平台开启出租客账号
     * @param rentersId
     * @param platformId
     */
    @Override
    public void startState(Integer rentersId,Integer platformId) {
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()==StateData.RENDERS_STATE_ENABLE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_ENABLE);
        }
        Renters renters1 = new Renters();
        renters1.setRentersState(StateData.RENDERS_STATE_ENABLE);
        rentersMapper.updateById(renters1);
    }

    /***
     * 平台禁用出租客账号
     * @param rentersId
     * @param platformId
     */
    @Override
    public void disableState(Integer rentersId, Integer platformId) {
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()==StateData.RENDERS_STATE_DISABLE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_DISABLE);
        }
        Renters renters1 = new Renters();
        renters1.setRentersState(StateData.RENDERS_STATE_DISABLE);
        rentersMapper.updateById(renters1);
    }

    /***
     * 平台删除出租客账号
     * @param rentersId
     * @param platformId
     */
    @Override
    public void deleteState(Integer rentersId, Integer platformId) {
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()==StateData.RENDERS_STATE_DELETE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_DELETE);
        }
        Renters renters1 = new Renters();
        renters1.setRentersState(StateData.RENDERS_STATE_DELETE);
        rentersMapper.updateById(renters1);
    }

    /***
     * 查询出租客账号
     * @param form
     * @return
     */
    @Override
    public PageInfo selectRenters(SelectRenterForm form) {
        Page<Renters> page = new Page<>(form.getPageNum()==null?form.getPageNum():1, form.getPageSize()!=null?form.getPageSize():4);
        QueryWrapper<Renters> wrapper = new QueryWrapper<>();
        wrapper.like("renters_account",form.getRentersAccount());
        Renters renters = rentersMapper.selectOne(wrapper);
        if (renters==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        List<Renters> list = rentersMapper.selectPage(page, wrapper).getRecords();
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(list);
        return pageInfo;
    }

}
